package com.example.gsq.news.ui.activity;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.DragEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.Toast;

import com.example.gsq.news.R;
import com.example.gsq.news.adapter.TabFragmentPagerAdapter;
import com.example.gsq.news.base.BaseActivity;
import com.example.gsq.news.base.BaseFragment;
import com.example.gsq.news.ui.fragment.NewsFragment;
import com.example.gsq.news.util.C;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    private RelativeLayout homeLayout, kejiLayout, tiyuLayout, shehuiLayout, guoneiLayout, yuleLayout, junshiLayout;
    private Switch homeSwitch, kejiSwitch, tiyuSwitch, shehuiSwitch, guoneiSwitch, yuleSwitch, junshiSwitch;

    private DrawerLayout mDrawerLayout;
//    private NavigationView mNavigationView;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private Toolbar mToolBar;


    private List<BaseFragment> mFragmentList;
    private List<Integer> mTabTileList;
    private List<String> urlStringList;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private TabFragmentPagerAdapter mPagerAdapter;

    private String refreshUrl;

    private LayoutOnClickListener mLayoutOnClickListener;

    private SwitchOnCheckChangedListener mSwitchListener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);

        setContentView(R.layout.layout_drawer);

        initViews();

        refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_TOP);

        mFragmentList = new ArrayList<>();
        mPagerAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        mTabTileList = new ArrayList<>();
        urlStringList = new ArrayList<>();

        SharedPreferences mPreferences = getSharedPreferences("urlStringPreferences", Context.MODE_PRIVATE);
        String uslString = mPreferences.getString("urlString", "");
        String titleString = mPreferences.getString("titleString", "");
        if (!uslString.equals("") && !titleString.equals("")) {
            String[] urlArray = uslString.split(",");
            String[] tabIdArray = titleString.split(",");
            for (String url : urlArray) {
                urlStringList.add(url);
                NewsFragment fragment = new NewsFragment();
                Bundle bundle = new Bundle();
                bundle.putString("fragmentUrl", url);
                fragment.setArguments(bundle);
                mFragmentList.add(fragment);
            }
            for (String tabId : tabIdArray) {
                mTabTileList.add(Integer.parseInt(tabId));
                Switch mSwitch = (Switch) getWindow().getDecorView().findViewWithTag(Integer.parseInt(tabId));
                if(mSwitch != null){
                    mSwitch.setChecked(true);
                }
            }
        } else {
            NewsFragment fragment = new NewsFragment();
            Bundle bundle = new Bundle();
            bundle.putString("fragmentUrl", C.getNewsUrl(C.News.NEWS_TYPE_TOP));
            fragment.setArguments(bundle);
            mFragmentList.add(fragment);
            urlStringList.add(C.getNewsUrl(C.News.NEWS_TYPE_TOP));
            mTabTileList.add(R.string.home);
        }
        mTabLayout.setTabTextColors(ColorStateList.valueOf(Color.WHITE));
        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setOffscreenPageLimit(0);
        mViewPager.setAdapter(mPagerAdapter);
        addTabTitles();

    }

    private void initViews() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
        mToolBar = (Toolbar) findViewById(R.id.tool_bar);
        mToolBar.setTitleTextColor(Color.WHITE);
        mToolBar.setTitle("");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();
//        setupDrawerContent(mNavigationView);

        mViewPager = (ViewPager) findViewById(R.id.fragment_pager);
        mTabLayout = (TabLayout) findViewById(R.id.tab_layout);

        homeLayout = (RelativeLayout) findViewById(R.id.layout_home);
        kejiLayout = (RelativeLayout) findViewById(R.id.layout_keji);
        tiyuLayout = (RelativeLayout) findViewById(R.id.layout_tiyu);
        shehuiLayout = (RelativeLayout) findViewById(R.id.layout_shehui);
        guoneiLayout = (RelativeLayout) findViewById(R.id.layout_guonei);
        yuleLayout = (RelativeLayout) findViewById(R.id.layout_yule);
        junshiLayout = (RelativeLayout) findViewById(R.id.layout_junshi);

        mLayoutOnClickListener = new LayoutOnClickListener();
        homeLayout.setOnClickListener(mLayoutOnClickListener);
        kejiLayout.setOnClickListener(mLayoutOnClickListener);
        tiyuLayout.setOnClickListener(mLayoutOnClickListener);
        shehuiLayout.setOnClickListener(mLayoutOnClickListener);
        guoneiLayout.setOnClickListener(mLayoutOnClickListener);
        yuleLayout.setOnClickListener(mLayoutOnClickListener);
        junshiLayout.setOnClickListener(mLayoutOnClickListener);


        homeSwitch = (Switch) findViewById(R.id.switch_home);
        homeSwitch.setTag(R.string.home);
        kejiSwitch = (Switch) findViewById(R.id.switch_keji);
        kejiSwitch.setTag(R.string.keji);
        tiyuSwitch = (Switch) findViewById(R.id.switch_tiyu);
        tiyuSwitch.setTag(R.string.tiyu);
        shehuiSwitch = (Switch) findViewById(R.id.switch_shehui);
        shehuiSwitch.setTag(R.string.shehui);
        guoneiSwitch = (Switch) findViewById(R.id.switch_guonei);
        guoneiSwitch.setTag(R.string.guonei);
        yuleSwitch = (Switch) findViewById(R.id.switch_yule);
        yuleSwitch.setTag(R.string.yule);
        junshiSwitch = (Switch) findViewById(R.id.switch_junshi);
        junshiSwitch.setTag(R.string.junshi);

        mSwitchListener = new SwitchOnCheckChangedListener();
        homeSwitch.setOnCheckedChangeListener(mSwitchListener);
        kejiSwitch.setOnCheckedChangeListener(mSwitchListener);
        tiyuSwitch.setOnCheckedChangeListener(mSwitchListener);
        shehuiSwitch.setOnCheckedChangeListener(mSwitchListener);
        guoneiSwitch.setOnCheckedChangeListener(mSwitchListener);
        yuleSwitch.setOnCheckedChangeListener(mSwitchListener);
        junshiSwitch.setOnCheckedChangeListener(mSwitchListener);

    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        int title = 0;
                        switch (menuItem.getItemId()) {
                            case R.id.navigation_home:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_TOP);
                                title = R.string.home;
                                break;
                            case R.id.navigation_keji:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_KEJI);
                                title = R.string.keji;
                                break;
                            case R.id.navigation_tiyu:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_TIYU);
                                title = R.string.tiyu;
                                break;
                            case R.id.navigation_shehui:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_SHEHUI);
                                title = R.string.shehui;
                                break;
                            case R.id.navigation_guonei:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_GUONEI);
                                title = R.string.guonei;
                                break;
                            case R.id.navigation_yule:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_YULE);
                                title = R.string.yule;
                                break;
                            case R.id.navigation_junshi:
                                refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_JUNSHI);
                                title = R.string.junshi;
                                break;
                        }
                        if (!urlStringList.contains(refreshUrl)) {
                            urlStringList.add(refreshUrl);
                            NewsFragment fragment = new NewsFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("fragmentUrl", refreshUrl);
                            fragment.setArguments(bundle);
                            mFragmentList.add(fragment);
                            mPagerAdapter.notifyDataSetChanged();
                            mTabTileList.add(title);
                            addTabTitles();
                        }
                        mViewPager.setCurrentItem(urlStringList.indexOf(refreshUrl), true);
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }


    class LayoutOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {

        }
    }

    class SwitchOnCheckChangedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int title = 0;
            switch (buttonView.getId()) {
                case R.id.switch_home:
                    break;
                case R.id.switch_keji:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_KEJI);
                    title = R.string.keji;
                    break;
                case R.id.switch_tiyu:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_TIYU);
                    title = R.string.tiyu;
                    break;
                case R.id.switch_shehui:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_SHEHUI);
                    title = R.string.shehui;
                    break;
                case R.id.switch_guonei:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_GUONEI);
                    title = R.string.guonei;
                    break;
                case R.id.switch_yule:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_YULE);
                    title = R.string.yule;
                    break;
                case R.id.switch_junshi:
                    refreshUrl = C.getNewsUrl(C.News.NEWS_TYPE_JUNSHI);
                    title = R.string.junshi;
                    break;
            }
            if (isChecked) {
                if (!urlStringList.contains(refreshUrl)) {
                    urlStringList.add(refreshUrl);
                    NewsFragment fragment = new NewsFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("fragmentUrl", refreshUrl);
                    fragment.setArguments(bundle);
                    mFragmentList.add(fragment);
                    mTabTileList.add(title);
                }
            } else {
                if (urlStringList.contains(refreshUrl)) {
                    int index = urlStringList.indexOf(refreshUrl);
                    urlStringList.remove(index);
                    mTabTileList.remove(index);
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
                    transaction.remove(mFragmentList.get(index));
                    transaction.commit();
                    mFragmentList.remove(index);
                    mPagerAdapter = null;
                    mPagerAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
                    mViewPager.setAdapter(mPagerAdapter);
                }
            }
            mPagerAdapter.notifyDataSetChanged();
            addTabTitles();
        }
    }

    private void addTabTitles() {
        mTabLayout.removeAllTabs();
        for (int title : mTabTileList) {
            mTabLayout.addTab(mTabLayout.newTab().setText(title));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SharedPreferences mPreferences = getSharedPreferences("urlStringPreferences", Context.MODE_PRIVATE);
        StringBuffer urlListString = new StringBuffer();
        StringBuffer titleIdListString = new StringBuffer();
        for (String url : urlStringList) {
            urlListString.append(url + ",");
        }
        for (int tabId : mTabTileList) {
            titleIdListString.append(tabId + ",");
        }
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("urlString", urlListString.toString());
        editor.putString("titleString", titleIdListString.toString());
        editor.commit();
    }
}
